package com.tnovoselec.android.ui;



import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.RectF;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;


public class ImageViewRounded extends ImageView {

    private final static float DEFAULT_RADIUS = 5f;

    private float radius;
    private Path clipPath;
    private RectF clipRect;

    public ImageViewRounded(Context context) {
	this(context, null);
    }

    public ImageViewRounded(Context context, AttributeSet attrs) {
	this(context, attrs, 0);
    }

    public ImageViewRounded(Context context, AttributeSet attrs, int defStyle) {
	super(context, attrs, defStyle);

	final float density = getResources().getDisplayMetrics().density;
	try {
	    final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ImageViewRounded, defStyle, 0);
	    radius = a.getDimension(R.styleable.ImageViewRounded_radius, DEFAULT_RADIUS * density);
	    a.recycle();
	    if (radius > 0 && Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
		this.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
	    }
	} catch (Exception e) {
	    radius = DEFAULT_RADIUS * density;
	}
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
	super.onSizeChanged(w, h, oldw, oldh);
	clipRect = new RectF(0, 0, w, h);
	clipPath = new Path();
	clipPath.addRoundRect(clipRect, radius, radius, Path.Direction.CW);
    }

    @Override
    protected void onDraw(Canvas canvas) {
	if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
	    if (radius > 0 && !canvas.isHardwareAccelerated()) {
		canvas.clipPath(clipPath);
	    }
	}
	super.onDraw(canvas);
    }

    /**
     * 
     * @return corner rounding radius
     */
    public float getRadius() {
	return radius;
    }

    /**
     * Set corner rounding radius. Negative values are clipped to 0
     * 
     * @param radius
     */
    public void setRadius(float radius) {
	this.radius = Math.max(0, radius);
    }

}
